import {Loading, Message, MessageBox} from 'element-ui'
import store from '../store'

// 存储不回掉
const setData = (k, v) => store.commit('put', {k, v})
//存储回调
const syncSetData = (k, v) => store.dispatch('put',{ k, v})
const getData = (k, v) => store.getters.get(k, v)
const removeData = k => store.commit('clear', k)
const syncRemoveData = k => store.dispatch('clear', k)

const confirm = (obj, callback) => {
  MessageBox.confirm(
    obj.content || '',
    obj.title || '提示',
    {
      showCancelButton: obj.showCancelButton || false,
      confirmButtonText: obj.ok ? obj.ok : '确认',
      cancelButtonText: obj.cancel ? obj.cancel : '取消',
      type: obj.type ? obj.type : 'warning'
    }
  ).then(callback)
}

const Toast = (title, type) => {
  Message({
    message: title,
    type: type ? type : 'error',
    duration: 5 * 1000
  })
}
const showToast = (obj) => {
  obj.type = obj.type ? obj.type : 'error'
  obj.duration = obj.duration ? obj.type : 5 * 1000
  Message(obj)
}
let loading //定义loading变量
const startLoading = (msg) => { //使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: msg ? msg : '努力加载中...',
    background: 'rgba(0, 0, 0, 0.5)'
  })
}

const hideLoading = () => { //使用Element loading-close 方法
  loading && loading.close()
}

// 获取指定时间
const getTime = day => {
  day = day || 0
  let d = new Date()
  let date = new Date(d)
  date.setDate(d.getDate() + day)
  return date
}
// 转化时间
const getDate = time => {
  if (!time || time === '~') return '~'

  return time.getFullYear() + '年' +
    (time.getMonth() + 1) +
    '月' + time.getDate() + '日'
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

const random = function generateMixed (n) {
  let res = ''
  for (let i = 0; i < n; i++) {
    const id = Math.ceil(Math.random() * 35)
    res += chars[id]
  }
  return res
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
export default {
  setData,
  syncSetData,
  getData,
  removeData,
  syncRemoveData,
  confirm,
  formatTime,
  getTime,
  getDate,
  Toast,
  showToast,
  formatNumber,
  random,
  startLoading,
  hideLoading
}
